<?php
/*************************************************************************************
 *
 *	FileName: header_php.php
 *	Desc    : create or update the list
 *	Author  : Seal
 *	Date    : 2010-1-30
 *
 *************************************************************************************/
	
	$errmsg = GetMessageStack();

/***************************************************************************************
 *	Display the list information to edit
 ***************************************************************************************/
	if( isset($_GET['lid']) ) {
		extract( QueryList( $_GET['lid'] ) ) ;
		return;
	}
			
/***************************************************************************************
 *	process the add or edit action
 ***************************************************************************************/
	if( isset($_POST['action']) )
	{
		$list_name = $_POST['list_name'];
			
		$list_desc = $_POST['list_desc'];
			
		$list_label = $_POST['list_label'];
		
		$list_labels = explode( ' ', $list_label );
		$list_labels = array_unique( $list_labels );
		foreach( $list_labels as $key => $value )
			$value = trim($value);
			
		$list_label = implode(' ', $list_labels );
		
		$list_content = split( ',' , rtrim( $_POST['list_content'], ',' ) );
			
		$list_priority = split( ',' , rtrim( $_POST['list_priority'], ',' ) );
			
		$list_cate = split( ',' , rtrim( $_POST['list_cate'], ',' ) );
					
		if( count($list_content) != count($list_cate) ||
			count( $list_content) != count( array_unique($list_content) ) )
		{
			$errmsg->add( $page_base, "评单内容项有错误(0)！");
		}
		
		if( count($list_content) > 30 )
			$errmsg->add( $page_base, "不能添加超过30个评单项目！");
			
		if( count($list_content) < 3 )
			$errmsg->add( $page_base, "至少要添加3个评单项目！");
	
	
		if( $_POST['action'] == 'edit_list' )
			$list_id =  $_POST['lid'];
		
		
		if( IsParaOK() && $errmsg->size($page_base) == 0 )
		{
			$return = true;
			if( $_POST['action'] == 'create_list' )
				$return = ProcessCreate();
			else if( $_POST['action'] == 'edit_list' )
				$return = ProcessEdit();
	
			if( $return !== false )
			{
				$msg = sprintf( '<script>parent.location.href="%s";</script>', $return );
				echo $msg;
				edp_exit();
			}
				
		}
			
		if( $errmsg->size($page_base) > 0 )
		{
			$msg = sprintf( '<script>parent.showMessage("%s");</script>', str_replace( '"', '\"', $errmsg->getMessage($page_base) ) );
			echo $msg;
			edp_exit();
		}		
	}

	
/***************************************************************************************
 *	functions used in this page
 ***************************************************************************************/
	function QueryList( $listId)
	{
		global  $errmsg, $page_base;
		
		$listDAO = GetListDAO();
		$list  = $listDAO->GetListByLid( $listId );
		$authorId = $list['user_id'];
		
		if( $authorId === false || $authorId != GetLoginUserID() ){
			$errmsg->add( $page_base, "没有权限编辑此评单内容！");
			echo "没有权限编辑此评单内容！";
			edp_exit();
			return -1;
		}
		
		$listShop = array();
		$listProduct = array();
		
		$listArray = split( ' ', trim($list['item_priority']) );
		foreach( $listArray as $k => $v )
		{
			$tempArray = split( ':', $v );
			$listItems[] = array(
				'id' => $tempArray[0],
				'cate' => $tempArray[1]			
			);
			
			if( $tempArray[1] == 0 )
				$listShop[] = $tempArray[0];
			else 
				$listProduct[] = $tempArray[0];
		}
		
		if( count($listShop) )
		{
			$shopDAO = GetShopDAO();
			$listShops = $shopDAO->GetShopSimpleInfo($listShop);
			if( $listShops )
			{
				foreach( $listShops as $key => $value )
				{
					$listShop[ $value['id'] ] = array(
						'name' => $value['shop_name'],
						'reality' => $value['reality'],
						'service' => $value['service'],
						'velocity' => $value['velocity'],
						'rate' => $value['rate'],
					);
				}
			}
		}
		
		if( count($listProduct) )
		{
			$productDAO = GetProductDAO();
			$listProducts = $productDAO->GetProductSimpleInfo($listProduct);
			if( $listProducts )
			{
				foreach( $listProducts as $key => $value )
				{
					$listProduct[ $value['id'] ] = array(
						'name' => $value['product_name'] . '(' . 
								$value['shop_name']  . ')',
						'reality' => $value['reality'],
						'service' => $value['service'],
						'velocity' => $value['velocity'],
						'rate' => $value['rate'],
					);
					
				}
			}
		}
		
		return compact( "list", "listShop", "listProduct", "listItems" );
		
	}
	
	function ProcessCreate()
	{
		global $errmsg, $list_cate, $list_content, $list_priority, 
			$list_name, $list_desc, $list_label,$page_base;
		
		
		foreach( $list_cate as $key => $value )
		{
			if( intval($value) != 0 && intval($value) != 1 )
			{
				$errmsg->add( $page_base, "评单内容项有错误(1)！");
				return false;
			}
		}
			
		for( $i = 0; $i < count($list_content); $i++ )
		{
			if( is_numeric($list_content[$i]) )
			{
				$list_array[] =  array(
					"id" => $list_content[$i],
					"priority" => intval($list_priority[$i]),
					"category" => $list_cate[$i]
				);
			}
		}
		
		if( count($list_array) <3 )
		{
			$errmsg->add( $page_base, "至少要添加三项有效的评单内容！");
			return false;
		}
		
		$shop_list = array();
		$product_list = array();
		
		foreach( $list_array as $key => $value )
		{
			if( $value['category'] == '0')
				$shop_list[ $value['id'] ] = $value;
			else
				$product_list[ $value['id'] ] = $value;
		}

				
		$keys_shop = implode( ',' , array_keys( $shop_list ) );
		$keys_product = implode( ',', array_keys( $product_list ) );
		
				
		if( edp_is_empty_string($keys_shop) == false )
		{
			// shop list validation
			$shopDAO = GetShopDAO();
			$shopResult = $shopDAO->GetShopForValidation( $keys_shop );
			
			if( $shopResult )
			{
				foreach( $shopResult as $key => $value )
				{
					$result_id = $value['id'];
					if( array_key_exists( $result_id, $shop_list ) )
					{
						
						$shop_list[$result_id]['plat_id'] = $value['plat_id'];
						$shop_list[$result_id]['logo_url'] = $value['logo_url'];
					}
					else
						remove_id( $result_id, $list_array, 0 );
				}
			}
			
			$shop_list = array_filter( $shop_list, "filter_out_list" );
		}
		
		if( edp_is_empty_string($keys_product) == false )
		{
			// product list validation
			$productDAO = GetProductDAO();
			$productResult = $productDAO->GetProductForValidation( $keys_product );
			
			if( $productResult )
			{
				foreach( $productResult as $key => $value )
				{
					$result_id = $value['id'];
					
					if( array_key_exists( $result_id, $product_list ) )
						$product_list[$result_id]['pic_path'] = $value['pic_path'];
					else
						remove_id( $result_id, $list_array, 1 );
				}
			}
			
			$product_list = array_filter( $product_list, "filter_out_list" );
			
		}
		
		foreach( $list_array as $k => $v )
	    		$prios[$k] = $v['priority'];

	    array_multisort( $prios, SORT_NUMERIC, SORT_ASC, $list_array );
	    	
		$listDAO = GetListDAO();
		$list_id = $listDAO->AddNewList( 
			edp_db_input($list_name),
			edp_db_input($list_desc),
			edp_db_input($list_label),
			$shop_list,
			$product_list,
			$list_array
		);
		
		$paras['lid'] = $list_id;
		$message = GetEventDispatcher();
		$message->Notify( GetLoginUserID(), CREATE_LIST, $paras );
		
		
		return edp_href_link("list_info", "lid=$list_id");
			
					
	}
	
	function ProcessEdit()
	{
		global $errmsg, $list_cate, $list_content, $list_priority, 
			$list_name, $list_desc, $list_label, $list_id, $page_base;
		
		$authorId = GetListDAO()->GetListAuthorId( $list_id );
		if( $authorId === false || $authorId != GetLoginUserID() ){
			$errmsg->add( $page_base, "没有权限编辑此评单内容！");
			return false;
		}
			
		foreach( $list_cate as $key => $value )
		{
			if( intval($value) != 0 && intval($value) != 1 )
			{
				$errmsg->add( $page_base, "评单内容项有错误(1)！");
				return false;
			}
		}
			
		for( $i = 0; $i < count($list_content); $i++ )
		{
			if( is_numeric($list_content[$i]) )
			{
				$list_array[] =  array(
					"id" => $list_content[$i],
					"priority" => intval($list_priority[$i]),
					"category" => $list_cate[$i]
				);
			}
		}
		
		if( count($list_array) == 0)
		{
			$errmsg->add( $page_base, "至少要添加一项有效的评单内容！");
			return false;
		}
		
		$listDAO = GetListDAO();
		$ori_item = split( ' ', trim($listDAO->GetListItemPriority( $list_id )) );
		
		for( $i = 1; $i <= count($ori_item); $i++ )
		{
			list( $id, $cate ) = split( ':', $ori_item[$i-1] );
			$ori_list[] = array(
				"id" => $id,
				"category" => $cate,
				"priority" => $i
			);
		}
		
		// find added items
		$add_items = array();
		foreach( $list_array as $k => $v )
		{
			if( find_item_by_id( $v['id'], $ori_list, $v['category'] ) == false )
			{
				$add_items[] = array(
					"id" => $v['id'],
					"category" => $v['category'],
					"priority" => $v['priority']
				);
			}
		}
		
		// find deleted items
		$delete_items = array();
		foreach( $ori_list as $k => $v )
		{
			if( find_item_by_id( $v['id'], $list_array, $v['category'] ) == false )
			{
				$delete_items[] = $v['id'];
			}
		}
		
		
		$shop_list = array();
		$product_list = array();
		
		foreach( $list_array as $key => $value )
			if( $value['category'] == '0')
				$shop_list[ $value['id'] ] = $value;
			else
				$product_list[ $value['id'] ] = $value;

				
		$keys_shop = implode( ',' , array_keys( $shop_list ) );
		$keys_product = implode( ',', array_keys( $product_list ) );
		
		if( edp_is_empty_string($keys_shop) == false )
		{
			// shop list validation
			$shopDAO = GetShopDAO();
			$shopResult = $shopDAO->GetShopForValidation( $keys_shop );
			
			if( $shopResult )
			{
				foreach( $shopResult as $key => $value )
				{
					$result_id = $value['id'];
					if( array_key_exists( $result_id, $shop_list ) )
					{
						
						$shop_list[$result_id]['plat_id'] = $value['plat_id'];
						$shop_list[$result_id]['logo_url'] = $value['logo_url'];
					}
					else
					{
						remove_id( $result_id, $add_items, 0 );
						remove_id( $result_id, $list_array, 0);
					}
				}
			}
			
			$shop_list = array_filter( $shop_list, "filter_out_list" );
		}
		
		if( edp_is_empty_string($keys_product) == false )
		{
			// product list validation
			$productDAO = GetProductDAO();
			$productResult = $productDAO->GetProductForValidation( $keys_product );
			
			if( $productResult )
			{
				foreach( $productResult as $key => $value )
				{
					$result_id = $value['id'];
					
					if( array_key_exists( $result_id, $product_list ) )
						$product_list[$result_id]['pic_path'] = $value['pic_path'];
					else
					{
						remove_id( $result_id, $add_items, 1 );
						remove_id( $result_id, $list_array, 1 );
					}
				}
			}
			
			$product_list = array_filter( $product_list, "filter_out_list" );
		}
		
		foreach( $list_array as $k => $v )
	    		$prios[$k] = $v['priority'];

	    array_multisort( $prios, SORT_NUMERIC, SORT_ASC, $list_array );
	    	
		$listDAO = GetListDAO();
		$listDAO->UpdateList( 
			$list_id,
			edp_db_input($list_name),
			edp_db_input($list_desc),
			edp_db_input($list_label),
			$shop_list,
			$product_list,
			$list_array,
			$add_items,
			$delete_items
		);
		
		return edp_href_link("list_info", "lid=$list_id");
			
					
	}

	function remove_id( $id, &$array, $plat_id )
	{
		foreach( $array as $k => $v )
		{
			if( $v['id'] == $id && $v['plat_id'] == $plat_id )
			{
				unset( $array[$k] );
				return;
			}
		}
		
	}
	
	function find_item_by_id( $id, &$array, $plat_id )
	{
		foreach( $array as $k => $v )
			if( $v['id'] == $id && $v['category'] == $plat_id )
				return true;
				
		return false;
	}
	
	
	function filter_out_list( $val )
	{
		return isset($val['logo_url']) || isset($val['pic_path']);
	}
	
	function sort_by_priority( $a, $b )
	{
		return $a["priority"] > $b['priority'];
	}
?>